/**
 * Project  PersonalMediaDevice
 * 
 */
package ua.at.tsvetkov.views;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Simple view for show texting clock in 24h format "HH:MM"
 * @author Alexandr Tsvetkov 15.01.2013
 */
public class ViewClock extends TextView {

	private static final int					SECOND	= 1000;
	private static final int					MINUTE	= 60 * SECOND;
	private static final SimpleDateFormat	sdf		= new SimpleDateFormat("HH:mm", Locale.GERMAN);

	private Timer									timer;

	/**
	 * @param context
	 */
	public ViewClock(Context context) {
		super(context);
		setTime();
	}

	/**
	 * @param context
	 * @param attrs
	 */
	public ViewClock(Context context, AttributeSet attrs) {
		super(context, attrs);
		setTime();
	}

	/**
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */
	public ViewClock(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setTime();
	}

	private void setTime() {
		setText("00:00");
	}

	/**
	 * Start changing time string
	 * @param activity
	 */
	public void start(final Activity activity) {
		setText(sdf.format(new Date()));
		timer = new Timer();
		long delay = SECOND - (System.currentTimeMillis() % SECOND);
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				activity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						setText(sdf.format(new Date()));
					}
				});
			}
		}, delay, MINUTE);
	}

	/**
	 * Stop changing time string
	 */
	public void stop() {
		timer.purge();
	}
}
